import React, { useState, useEffect } from 'react';
import { ShoppingCart, User, Package, LogOut, Heart, Star, Plus, Minus, X, Check } from 'lucide-react';
import axios from 'axios';
// Types
interface Product {
  id: number;
  name: string;
  price: number;
  imageUrl: string;
  description: string;
  stock: number;
  isFlashSale: boolean;
  flashSaleStartTime: string | null;
  flashSaleEndTime: string | null;
  tags: string;
}

interface CartItem {
  id: number;
  userId: number;
  productId: number;
  quantity: number;
  product: Product;
}

interface Order {
  id: number;
  orderNo: string;
  userId: number;
  productId: number;
  quantity: number;
  totalAmount: number;
  status: number; // 0：待支付，1：已支付，2：取消支付
  productImageUrl: string;
  createdTime: string;
  product?: Product;
}

interface User {
  id: number;
  username: string;
  createdTime: string;
  updatedTime: string;
}

// API Base URL
const API_BASE_URL = 'http://115.190.33.252:8089/api';

// Components
const LoginPage: React.FC<{ onLogin: (user: User) => void }> = ({ onLogin }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const response = await fetch(`${API_BASE_URL}/user/login?username=${email}`, {
        method: 'POST'
      });
      const data = await response.json();
      if (data.code === 200) {
        onLogin(data.data);
      }
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-100 flex items-center justify-center p-4">
      <div className="bg-white/80 backdrop-blur-lg p-8 rounded-2xl shadow-2xl border border-white/20 w-full max-w-md">
        <div className="text-center mb-8">
          <div className="bg-gradient-to-r from-blue-600 to-indigo-600 w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <ShoppingCart className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent">
            智慧商城
          </h1>
          <p className="text-gray-600 mt-2">欢迎回来，请登录您的账户</p>
        </div>

        <form onSubmit={handleLogin} className="space-y-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">邮箱地址</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
              placeholder="请输入邮箱地址"
              required
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">密码</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200"
              placeholder="请输入密码"
              required
            />
          </div>

          <button
            type="submit"
            className="w-full bg-gradient-to-r from-blue-600 to-indigo-600 text-white py-3 px-6 rounded-xl hover:shadow-lg transform hover:scale-105 transition-all duration-200 font-medium"
          >
            立即登录
          </button>
        </form>

        <div className="mt-6 text-center text-sm text-gray-500">
          <p>演示账户：任意邮箱和密码即可登录</p>
        </div>
      </div>
    </div>
  );
};

const ProductCard: React.FC<{
  product: Product;
  onAddToCart: (product: Product) => void;
  onBuyNow: (product: Product) => void;
}> = ({ product, onAddToCart, onBuyNow }) => {
  return (
    <div className="bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 overflow-hidden group">
      <div className="relative overflow-hidden">
        {/* 商品图片部分 */}
        <div className="aspect-square bg-gray-100 relative">
          <img
            src={'http://115.190.33.252:8089'+product.imageUrl || '/placeholder-product.jpg'}
            alt={product.name}
            className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
            onError={(e) => {
              (e.target as HTMLImageElement).src = '/placeholder-product.jpg';
            }}
          />
        </div>
        
        {product.isFlashSale && (
          <div className="absolute top-3 left-3 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded">
            限时抢购
          </div>
        )}
        <div className="absolute top-3 right-3 bg-white/90 backdrop-blur-sm rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity">
          <Heart className="w-4 h-4 text-gray-600 hover:text-red-500 transition-colors cursor-pointer" />
        </div>
      </div>
      
      <div className="p-5">
        <div className="flex items-center justify-between mb-2">
          <span className="text-xs font-medium text-blue-600 bg-blue-50 px-2 py-1 rounded-full">
            {product.tags.split(',')[0]}
          </span>
          <div className="text-sm text-gray-600">
            库存: {product.stock}
          </div>
        </div>
        
        <h3 className="font-semibold text-gray-800 mb-2 line-clamp-1">{product.name}</h3>
        <p className="text-sm text-gray-600 mb-3 line-clamp-2">{product.description}</p>
        
        <div className="flex items-center justify-between">
          <span className="text-2xl font-bold text-orange-600">¥{product.price}</span>
          <div className="flex gap-2">
            <button
              onClick={() => onAddToCart(product)}
              className="bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-lg transition-colors"
            >
              <Plus className="w-4 h-4" />
            </button>
            <button
              onClick={() => onBuyNow(product)}
              className="bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white px-4 py-2 rounded-lg transition-all font-medium"
            >
              立即购买
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
const Navigation: React.FC<{
  currentPage: string;
  onPageChange: (page: string) => void;
  cartItemsCount: number;
  onLogout: () => void;
  user: User;
}> = ({ currentPage, onPageChange, cartItemsCount, onLogout, user }) => {
  const navItems = [
    { id: 'products', label: '商品', icon: Package },
    { id: 'cart', label: '购物车', icon: ShoppingCart, badge: cartItemsCount },
    { id: 'orders', label: '订单', icon: User }
  ];

  return (
    <nav className="bg-white/80 backdrop-blur-lg border-b border-white/20 sticky top-0 z-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-16">
          <div className="flex items-center space-x-2">
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 w-8 h-8 rounded-lg flex items-center justify-center">
              <ShoppingCart className="w-5 h-5 text-white" />
            </div>
            <span className="text-xl font-bold bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent">
              智慧商城
            </span>
          </div>

          <div className="flex items-center space-x-1">
            {navItems.map((item) => {
              const Icon = item.icon;
              return (
                <button
                  key={item.id}
                  onClick={() => onPageChange(item.id)}
                  className={`relative px-4 py-2 rounded-lg transition-all duration-200 flex items-center space-x-2 ${
                    currentPage === item.id
                      ? 'bg-blue-100 text-blue-600'
                      : 'text-gray-600 hover:bg-gray-100'
                  }`}
                >
                  <Icon className="w-5 h-5" />
                  <span className="hidden sm:inline">{item.label}</span>
                  {item.badge && item.badge > 0 && (
                    <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                      {item.badge}
                    </span>
                  )}
                </button>
              );
            })}
          </div>

          <div className="flex items-center space-x-3">
            <span className="text-sm text-gray-600 hidden sm:inline">欢迎，{user.username}</span>
            <button
              onClick={onLogout}
              className="text-gray-600 hover:text-red-600 transition-colors"
              title="退出登录"
            >
              <LogOut className="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>
    </nav>
  );
};

const ProductsPage: React.FC<{
  products: Product[];
  onAddToCart: (product: Product) => void;
  onBuyNow: (product: Product) => void;
}> = ({ products, onAddToCart, onBuyNow }) => {
  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-100">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">精选商品</h1>
          <p className="text-gray-600">发现优质好物，享受购物乐趣</p>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {products.map((product) => (
            <ProductCard
              key={product.id}
              product={product}
              onAddToCart={onAddToCart}
              onBuyNow={onBuyNow}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

const CartPage: React.FC<{
  cartItems: CartItem[];
  onUpdateQuantity: (productId: number, quantity: number) => void;
  onRemoveItem: (productId: number) => void;
  onCheckout: () => void;
  userId: number;
}> = ({ cartItems, onUpdateQuantity, onRemoveItem, onCheckout, userId }) => {
  const total = cartItems.reduce((sum, item) => sum + (item.product?.price || 0) * item.quantity, 0);

  if (cartItems.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-100 flex items-center justify-center">
        <div className="text-center">
          <ShoppingCart className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h2 className="text-2xl font-semibold text-gray-600 mb-2">购物车是空的</h2>
          <p className="text-gray-500">快去挑选您喜欢的商品吧！</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-100">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 className="text-3xl font-bold text-gray-800 mb-8">购物车</h1>

        <div className="bg-white rounded-2xl shadow-lg overflow-hidden">
          {cartItems.map((item) => (
            <div key={item.id} className="p-6 border-b border-gray-100 last:border-b-0">
              <div className="flex items-center space-x-4">
                
                <div className="flex-1">
                  <h3 className="font-semibold text-gray-800">{item.product?.name}</h3>
                  <p className="text-sm text-gray-600">{item.product?.description}</p>
                  <p className="text-lg font-bold text-orange-600 mt-1">¥{item.product?.price}</p>
                </div>
                <div className="flex items-center space-x-3">
                  <button
                    onClick={() => onUpdateQuantity(item.productId, Math.max(1, item.quantity - 1))}
                    className="bg-gray-100 hover:bg-gray-200 rounded-full p-1 transition-colors"
                  >
                    <Minus className="w-4 h-4" />
                  </button>
                  <span className="font-semibold min-w-[2rem] text-center">{item.quantity}</span>
                  <button
                    onClick={() => onUpdateQuantity(item.productId, item.quantity + 1)}
                    className="bg-gray-100 hover:bg-gray-200 rounded-full p-1 transition-colors"
                  >
                    <Plus className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => onRemoveItem(item.productId)}
                    className="text-red-500 hover:text-red-700 ml-4 transition-colors"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        <div className="bg-white rounded-2xl shadow-lg p-6 mt-6">
          <div className="flex justify-between items-center mb-4">
            <span className="text-lg font-semibold">总计</span>
            <span className="text-2xl font-bold text-orange-600">¥{total}</span>
          </div>
          <button
            onClick={onCheckout}
            className="w-full bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white py-3 px-6 rounded-xl transition-all font-medium"
          >
            立即结算
          </button>
        </div>
      </div>
    </div>
  );
};

const OrdersPage: React.FC<{ orders: Order[] ,fetchOrders}> = ({ orders,fetchOrders }) => {
  const getStatusColor = (status: number) => {
    switch (status) {
      case 0: return 'bg-yellow-100 text-yellow-800';
      case 1: return 'bg-green-100 text-green-800';
      case 2: return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusText = (status: number) => {
    switch (status) {
      case 0: return '待支付';
      case 1: return '已支付';
      case 2: return '已取消';
      default: return '未知状态';
    }
  };

 const handleCancelOrder = async (orderNo: string) => {
    try {
      const response = await axios.post(
        `http://115.190.33.252:8089/api/orders/${orderNo}/cancel`
      );
      
      if (response.status === 200) {
        // 更新订单状态为已取消
        alert('订单已成功取消');
      }
    } catch (error) {
      console.error('取消订单失败:', error);
      alert('取消订单失败，请重试');
    }finally{
      fetchOrders()
    }
  };

  const handlePayNow = async (orderNo: string) => {
    try {
      const response = await axios.post(
        `http://115.190.33.252:8089/api/orders/${orderNo}/pay`
      );
      
      if (response.status === 200) {
        // 更新订单状态为已支付

        console.log(response)
        fetchOrders()
        // 这里需要调用父组件的状态更新函数或使用状态管理
        alert('支付成功');
      }
    } catch (error) {
      console.error('支付失败:', error);
      alert('支付失败，请重试');
    }
  };

  if (orders.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-100 flex items-center justify-center">
        <div className="text-center">
          <Package className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h2 className="text-2xl font-semibold text-gray-600 mb-2">还没有订单</h2>
          <p className="text-gray-500">您的订单记录将显示在这里</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-100">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 className="text-3xl font-bold text-gray-800 mb-8">我的订单</h1>

        <div className="space-y-6">
          {orders.map((order) => (
            <div key={order.id} className="bg-white rounded-2xl shadow-lg overflow-hidden">
              <div className="p-6 border-b border-gray-100">
                <div className="flex justify-between items-center">
                  <div>
                    <h3 className="font-semibold text-gray-800">订单 #{order.orderNo}</h3>
                    <p className="text-sm text-gray-600">{order.createdTime}</p>
                  </div>
                  <div className="flex items-center space-x-4">
                    <span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(order.status)}`}>
                      {getStatusText(order.status)}
                    </span>
                    <span className="text-lg font-bold text-orange-600">¥{order.totalAmount}</span>
                  </div>
                </div>
              </div>
              
              <div className="p-6">
                <div className="flex items-center space-x-4 mb-4">
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-800">{order.product?.name || '商品'}</h4>
                    <p className="text-sm text-gray-600">数量: {order.quantity}</p>
                  </div>
                  <span className="font-semibold text-gray-800">¥{order.totalAmount}</span>
                </div>

                {/* Action buttons - only show for pending payment orders */}
                {order.status === 0 && (
                  <div className="flex justify-end space-x-3 pt-4 border-t border-gray-100">
                    <button
                      onClick={() => handleCancelOrder(order.orderNo)}
                      className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
                    >
                      取消订单
                    </button>
                    <button
                      onClick={() => handlePayNow(order.orderNo)}
                      className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors"
                    >
                      立即支付
                    </button>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// Main App Component
const App: React.FC = () => {
  const [user, setUser] = useState<User | null>(null);
  const [currentPage, setCurrentPage] = useState('products');
  const [products, setProducts] = useState<Product[]>([]);
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [orders, setOrders] = useState<Order[]>([]);

  // Fetch products on mount
  useEffect(() => {
    if (user) {
      fetchProducts();
      fetchCartItems();
      fetchOrders();
    }
  }, [user]);

  const fetchProducts = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/products`);
      const data = await response.json();
      if (data.code === 200) {
        setProducts(data.data);
      }
    } catch (error) {
      console.error('Error fetching products:', error);
    }
  };

  const fetchCartItems = async () => {
    if (!user) return;
    try {
      const response = await fetch(`${API_BASE_URL}/cart?userId=${user.id}`);
      const data = await response.json();
      if (data.code === 200) {
        // We need to fetch product details for each cart item
        const itemsWithProducts = await Promise.all(
          data.data.map(async (item: any) => {
            const productResponse = await fetch(`${API_BASE_URL}/products`);
            const productsData = await productResponse.json();
            const product = productsData.data.find((p: Product) => p.id === item.productId);
            return { ...item, product };
          })
        );
        setCartItems(itemsWithProducts);
      }
    } catch (error) {
      console.error('Error fetching cart items:', error);
    }
  };

  const fetchOrders = async () => {
    if (!user) return;
    try {
      const response = await fetch(`${API_BASE_URL}/orders/user/${user.id}`);
      const data = await response.json();
      if (data.code === 200) {
        // We need to fetch product details for each order
        const ordersWithProducts = await Promise.all(
          data.data.map(async (order: any) => {
            const productResponse = await fetch(`${API_BASE_URL}/products`);
            const productsData = await productResponse.json();
            const product = productsData.data.find((p: Product) => p.id === order.productId);
            return { ...order, product };
          })
        );
        setOrders(ordersWithProducts);
      }
    } catch (error) {
      console.error('Error fetching orders:', error);
    }
  };

  const handleLogin = (userData: User) => {
    setUser(userData);
    // Preload products after login
    fetch(`${API_BASE_URL}/products/preload`, { method: 'POST' }).catch(console.error);
  };

  const handleLogout = () => {
    setUser(null);
    setCurrentPage('products');
    setCartItems([]);
    setOrders([]);
  };

  const handleAddToCart = async (product: Product) => {
    if (!user) return;
    
    try {
      const response = await fetch(`${API_BASE_URL}/cart/add`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          productId: product.id,
          userId: user.id,
          quantity: 1
        })
      });
      
      if (response.ok) {
        fetchCartItems(); // Refresh cart items
      }
    } catch (error) {
      console.error('Error adding to cart:', error);
    }
  };

  const handleBuyNow = async (product: Product) => {
    if (!user) return;
    
    try {
      // First add to cart
      await fetch(`${API_BASE_URL}/cart/add`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          productId: product.id,
          userId: user.id,
          quantity: 1
        })
      });
      
      // Then proceed to checkout
      const purchaseResponse = await fetch(`${API_BASE_URL}/products/${product.id}/purchase?userId=${user.id}&quantity=1`, {
        method: 'POST'
      });
      
      if (purchaseResponse.ok) {
        setCurrentPage('orders');
        fetchCartItems(); // Refresh cart
        fetchOrders(); // Refresh orders
      }
    } catch (error) {
      console.error('Error buying now:', error);
    }
  };

  const handleUpdateQuantity = async (productId: number, quantity: number) => {
    if (!user) return;
    
    try {
      const response = await fetch(`${API_BASE_URL}/cart/update?userId=${user.id}&productId=${productId}&quantity=${quantity}`, {
        method: 'PUT'
      });
      
      if (response.ok) {
        fetchCartItems(); // Refresh cart items
      }
    } catch (error) {
      console.error('Error updating cart:', error);
    }
  };

  const handleRemoveItem = async (productId: number) => {
    if (!user) return;
    
    try {
      const response = await fetch(`${API_BASE_URL}/cart/update?userId=${user.id}&productId=${productId}&quantity=0`, {
        method: 'PUT'
      });
      
      if (response.ok) {
        fetchCartItems(); // Refresh cart items
      }
    } catch (error) {
      console.error('Error removing item:', error);
    }
  };

  const handleCheckout = async () => {
    if (!user || cartItems.length === 0) return;
    
    try {
      // For each item in cart, create an order
      for (const item of cartItems) {
        await fetch(`${API_BASE_URL}/products/${item.productId}/purchase?userId=${user.id}&quantity=${item.quantity}`, {
          method: 'POST'
        });
      }
      
      setCurrentPage('orders');
      fetchCartItems(); // Refresh cart
      fetchOrders(); // Refresh orders
    } catch (error) {
      console.error('Error during checkout:', error);
    }
  };

  if (!user) {
    return <LoginPage onLogin={handleLogin} />;
  }

  const cartItemsCount = cartItems.reduce((sum, item) => sum + item.quantity, 0);

  return (
    <div className="min-h-screen">
      <Navigation
        currentPage={currentPage}
        onPageChange={setCurrentPage}
        cartItemsCount={cartItemsCount}
        onLogout={handleLogout}
        user={user}
      />

      {currentPage === 'products' && (
        <ProductsPage
          products={products}
          onAddToCart={handleAddToCart}
          onBuyNow={handleBuyNow}
        />
      )}

      {currentPage === 'cart' && (
        <CartPage
          cartItems={cartItems}
          onUpdateQuantity={handleUpdateQuantity}
          onRemoveItem={handleRemoveItem}
          onCheckout={handleCheckout}
          userId={user.id}
        />
      )}

      {currentPage === 'orders' && <OrdersPage orders={orders} fetchOrders={fetchOrders} />}
    </div>
  );
};

export default App;